package com.example.demo.controller;

import com.example.demo.common.AppConstant;
import com.example.demo.common.HTTPResult;
import com.example.demo.common.PasswordUtil;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Userinfo;
import com.example.demo.entity.vo.UserinfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

/**
 * Created with IntelliJ IDEA.
 * Description: 用户操作控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;

    // 用户注册功能
    @RequestMapping("/reg")
    public HTTPResult reg(Userinfo userinfo) {
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername()) ||
                !StringUtils.hasLength(userinfo.getPassword())) {
            return HTTPResult.fail(-1, "非法参数");
        }
        if(userinfo.getUsername().length() < 5 || userinfo.getUsername().length() > 20
                || userinfo.getPassword().length() < 5 || userinfo.getPassword().length() > 20) {
            return HTTPResult.fail(-1, "用户名或密码长度异常！");
        }
        // 密码加密
        String finalString = PasswordUtil.encrypt(userinfo.getPassword());
        userinfo.setPassword(finalString);
        // 进行存储
        Integer result = userService.insertUser(userinfo);
        return HTTPResult.success(result);
    }

    // 登录功能，验证用户名和密码是否存在
    @RequestMapping("/login")
    public HTTPResult login(String username, String password, HttpServletRequest req) {
        if(!StringUtils.hasLength(username) ||
                !StringUtils.hasLength(password)) {
            return HTTPResult.fail(-1, "非法参数");
        }
        if(username.length() < 5 || username.length() > 20
                || password.length() < 5 || password.length() > 20) {
            return HTTPResult.fail(-1, "用户名或密码长度异常！");
        }
        // 获取数据库信息
        Userinfo user = userService.getUserByName(username);
        if(user != null && user.getId() >= 0) {
            if(PasswordUtil.decrypt(password, user.getPassword())) {
                // 验证用户身份通过
                // 返回前端前，隐藏敏感信息
                user.setPassword("");
                // 将用户存储到 session
                HttpSession session = req.getSession(true);
                session.setAttribute(AppConstant.USER_SESSION_KEY, user);
                return HTTPResult.success(user);
            }
        }
        // 用户不存在，返回
        return HTTPResult.fail(0,"用户名或密码错误！", null);
    }

    // 获取用户的用户名与文章数量
    @RequestMapping("/showinfo")
    public HTTPResult showinfo(HttpServletRequest request) {
        UserinfoVO userinfoVO = new UserinfoVO();
        // 1. 获取当前登录用户
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null) {
            return HTTPResult.fail(-1, "非法请求");
        }
        // Spring 提供的深克隆方法
        BeanUtils.copyProperties(userinfo,userinfoVO);
        // 得到用户发表文章的总数
        int artCount = articleService.getArtCountByUid(userinfo.getId());
        userinfoVO.setArtCount(artCount);
        return HTTPResult.success(userinfoVO);
    }

    // 获取用户的用户名和草稿信息
    @RequestMapping("/showdraftinfo")
    public HTTPResult showDraftInfo(HttpServletRequest request) {
        // 定义保存数据的返回对象
        UserinfoVO userinfoVO = new UserinfoVO();
        // 判断用户是否登录
        Userinfo userinfo = UserSessionUtils.getUserBySession(request);
        if(userinfo == null) {
            return HTTPResult.fail(-1, "非法请求");
        }
        // Spring 提供的深克隆方法，将 Session 中的用户信息复制到 userinfoVO
        BeanUtils.copyProperties(userinfo, userinfoVO);
        // 获取用户草稿数量
        Integer count = articleService.getDraftCountByUid(userinfo.getId());
        userinfoVO.setArtCount(count);
        return HTTPResult.success(200, userinfoVO);
    }

    // 注销用户
    @RequestMapping("/logout")
    public HTTPResult logout(HttpSession session) {
        session.removeAttribute(AppConstant.USER_SESSION_KEY);
        return HTTPResult.success("1");
    }

    // 根据用户 id 返回用户信息
    @RequestMapping("/showinfoid")
    public HTTPResult showinfoid(Integer id) {
        UserinfoVO userinfoVO = new UserinfoVO();
        if(id == null || id <= 0) {
            return HTTPResult.fail(-1, "参数异常");
        }
        // 获取基本用户信息
        Userinfo userinfo = userService.getUserById(id);
        if(userinfo == null) {
            return HTTPResult.fail(-2, "查无此人");
        }
        // 去除敏感信息
        userinfo.setPassword("");
        BeanUtils.copyProperties(userinfo, userinfoVO);
        // 得到用户发表文章的总数
        userinfoVO.setArtCount(articleService.getArtCountByUid(userinfo.getId()));
        return HTTPResult.success(userinfoVO);
    }
}
